package com.example.auction.util;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import androidx.annotation.RequiresApi;
import com.example.auction.R;

public class MyPublishedScrollView extends HorizontalScrollView {

    private int width;
    private ImageButton ibtn_publish_again;
    private ImageButton ibtn_close_auction;
    private ImageButton ibtn_delete_published_item;

    public MyPublishedScrollView(Context context) {
        super(context);
    }

    public MyPublishedScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyPublishedScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setOverScrollMode(OVER_SCROLL_NEVER);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public MyPublishedScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            ibtn_publish_again = findViewById(R.id.ibtn_publish_again);
            ibtn_close_auction = findViewById(R.id.ibtn_close_auction);
            ibtn_delete_published_item = findViewById(R.id.ibtn_delete_published_item);

            width = ibtn_delete_published_item.getWidth() * 2;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:

                //根据滑动距离判断是否显示删除按钮
                changeScrollx();
                return false;
            default:
                break;
        }
        return super.onTouchEvent(ev);
    }

    public void changeScrollx() {
        //触摸滑动的距离大于删除按钮宽度的一半
        if (getScrollX() >= (width / 12)) {
            //显示删除按钮
            this.smoothScrollTo(width, 0);
        } else {
            //隐藏删除按钮
            this.smoothScrollTo(0, 0);
        }
    }
}
